from openpyxl import load_workbook

from utils.handle_log import log
from utils.handle_path import case_path

class HandleExcel:
    def __init__(self,sheet_name):
        log.info(msg=f'用例excel正在读取的sheet：{sheet_name}')
        self.work_book = load_workbook(filename=case_path)
        self.sheet = self.work_book[sheet_name]

    #获取表头和所有测试用例数据
    def get_all_data(self):
        all_datas = list(self.sheet.iter_rows(values_only=True))
        title = all_datas[0]
        case_datas = all_datas[1:]

        case_list =[]
        for case_data in case_datas:
            case_list.append(dict(zip(title,case_data)))
        self.__close_excel()
        log.info(msg=f'测试用例数据：{case_list}')
        return case_list

    #将测试结果写入testCase.xlsx
    def write_result(self,rows,columns,result=None):
        self.sheet.cell(row=rows,column=columns).value=result
        self.__save_excel()
        self.__close_excel()

    #保存excel
    def __save_excel(self):
        self.work_book.save(filename=case_path)

    #关闭excel
    def __close_excel(self):
        self.work_book.close()

